import uniPopup from '@/components/uni-popup/uni-popup.vue' // 弹出框组件
import {
  compress
} from '@/utils/image-tools/index.js'
export default {
  components: {
    uniPopup, //弹出框组件
  },
  data() {
    return {
      isFocus: 1,
      typeshow: false,
      notCompanyName: false, //公司营业执照是否匹配
      notFace: false, //身份证人像面
      notBack: false, //身份证国徽面
      selector:
				// [{
				//      id: 0,
				//      name: '7迈车·养车（养护自营（7迈直营养护）、加盟门店（养护门店））'
				//    }, {
				//      id: 1,
				//      name: '7 迈车· 新车（ 4 S、 7 迈直营车、 汽贸店）'
				//    }, {
				//      id: 2,
				//      name: '7 迈车· 新车（ 主机厂、 车源商）'
				//    }, {
				//      id: 3,
				//      name: '美护保 / 精品供应商（ 7 迈直营美护保、 美护保精品供应商）'
				//    }],
				[{
				  id: 0,
				  name: '美保护精品供应商'
				},
				{
				  id: 1,
				  name: '7迈直营养护'
				},
				{
				  id: 2,
				  name: '车源商'
				},
				{
				  id: 3,
				  name: '汽贸店'
				},
				{
				  id: 4,
				  name: '4S店'
				},
				{
				  id: 5,
				  name: '7迈直营店'
				},
				{
				  id: 6,
				  name: '7迈直营美护保'
				},
				{
				  id: 7,
				  name: '主机厂'
				},
				{
				  id: 8,
				  name: '养护门店'
				}, {
				  id: 9,
				  name: '自助洗车加盟商'
				}, {
				  id: 10,
				  name: '自助洗车区域合作商'
				}
				// ,{
				// 	id: 11,
				// 	name: '自助洗车物业管理'
				// }
				],

      type: 0, //公司类型
      typename: '', //显示的类型
      imgCompanyName: '', //上传营业执照的公司名称
      stateSmallTitle: false, //公司类型
      imgurl: '', //营业执照图片地址
      faceimg: '', //正面
      backimg: '', //背面
      address: '', //营业执照地址
      mobile: '', //电话
      legalname: '', //法人姓名 ,
      isOwner: false,
      telPlaceholder: '法人手机号',
      telSmallTitle: false,
      telClearIcon: false,
      results: 1, //最开始匹配
      imgPolicy: '',
      imgAuthorization: '',
      imgHost: '',
      identityName: '', //已做个人认证的名字
      identityFaceimg: '', //已做个人认证身份证
      identityBackimg: '', //已做个人认证身份证
      addtype: 'new', //认证企业类型 new 注册认证 add 添加企业
      registerPhone: '', //登录时的手机号
      isCarwash: false, //是否为洗车商类型
    }
  },
  computed: {
    companyName() {
      return this.$store.state.user.companyName
    },

    checkImg() {
      if (this.isOwner && this.identityName !== this.legalname) {
        return false
      }
      if (this.companyName !== this.imgCompanyName) {
        return false
      }
      return true
    },

    listHeight() {
      let qccHeight = 80,
        yzcHeight = 80
      if (this.qcclist.length) {
        qccHeight = Math.min(this.qcclist.length, 4) * 80
      }
      if (this.list.length) {
        yzcHeight = Math.min(this.list.length, 4) * 80
      }
      return {
        qccHeight,
        yzcHeight,
      }
    },

    servicePhone() {
      return this.$store.state.user.servicePhone + ''
    },

    isDisabled() {
      if (this.typename && this.mobile && this.imgurl) {
        if (!/^1[3456789]\d{9}$/.test(this.mobile)) {
          return true
        }
        if (!this.checkImg) {
          return true
        }
        if (!this.isOwner && (!this.faceimg || !this.backimg)) {
          return true
        }
        return false
      }
      return true
    },
  },
  watch: {
    mobile(val) {
      if (val && !this.telClearIcon) {
        this.telClearIcon = true
      }
    },
  },

  onBackPress() {
    uni.redirectTo({
      url: '/pages_login/register/register?type=' + this.addtype + '&phone=' + this.registerPhone,
    })
    return true
  },

  onLoad(e) {
    this.addtype = e.type ? e.type : 'new'
    console.log(this.$store.state,e)
    this.registerPhone = e.phone ? e.phone : this.$store.state.user.userInfo.mobile
    if (e.companyName) {
      this.$store.commit('user/setCompanyInfo', {
        name: e.companyName,
        isJoinCompany: false,
      })
    } else {
      this.$store.dispatch('user/getUserCompany', {
        _this: this
      })
    }
    this.getUserIdentity()
  },
  methods: {
    //获取个人认证信息
    getUserIdentity() {
      this.$api.user.getIdentityName().then(res => {
        this.identityName = res.data.truename
        this.identityFaceimg = res.data.faceimg
        this.identityBackimg = res.data.backimg
      })
    },

    //打电话
    callPhone() {
      uni.makePhoneCall({
        phoneNumber: this.servicePhone,
      })
    },

    //清除输入
    clearIcon() {
      this.mobile = ''
      this.telSmallTitle = false //小标题
      this.telClearIcon = false
      this.telPlaceholder = '法人手机号' //input默认提示
    },

    // 打开picker
    openPicker() {
      this.typeshow = true
      this.isFocus = 2
    },

    //picker选择的值
    confirm(e) {
      this.type = this.selector[e].id
      this.typename = this.selector[e].name
      // console.log(this.type,this.typename)
      if (this.type === 9 || this.type === 10) {
        this.isCarwash = true
        this.isOwner = true
      } else {
        this.isCarwash = false
        this.isOwner = false
      }
      this.stateSmallTitle = true
      this.typeshow = false
    },

    //
    switchChange() {
      this.isFocus = 3
    },

    //实时监控法人电话
    telFocus(e) {
      this.telSmallTitle = true
      this.isFocus = 4
    },

    //法人电话失去焦点
    telBlur(e) {
      this.isFocus = 0
      if (e.detail.value) {
        if (e.detail.value.length !== 11) {
          uni.showToast({
            title: '请输入正确的手机号',
            duration: 2000,
            icon: 'none',
          })
        } else if (!/^1[3456789]\d{9}$/.test(e.detail.value)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
          })
        } else {
          this.mobile = e.detail.value
        }
      } else {
        this.telSmallTitle = false
        this.telClearIcon = false
      }
    },

    //选择图片
    uploadImage(type) {
      const _this = this
      _this.notCompanyName = false
      _this.notFace = false
      _this.notBack = false
      uni.showActionSheet({
        itemList: ['拍照', '打开相册'],
        success(res) {
          const cameraType = res.tapIndex ? 'album' : 'camera'
          uni.chooseImage({
            count: 1, // 默认9
            sizeType: 'compressed', // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [cameraType], // 从相册选择
            success: function(result) {
              // #ifdef APP-PLUS
              console.log(result)

              _this.compress(result.tempFiles[0]).then(resImg => {
                uni.showLoading({
                  title: '图片上传中~',
                })
                _this.$api.files
                  .uploadImg({
                    filePath: resImg,
                  })
                  .then(res => {
                    console.log('上传后的图片', res)
                    uni.hideLoading()
                    if (type === 0) {
                      // 营业执照

                      _this.imgurl = res.baseUrl + res.url
                      _this.readLicense(res.baseUrl + res.url)

                    } else if (type === 1) {
                      //法人身份证人像面
                      _this.faceimg = res.baseUrl + res.url

                    } else {
                      //法人身份证国徽面
                      _this.backimg = res.baseUrl + res.url

                    }

                  })
                  .catch(err => {
                    uni.hideLoading()
                    uni.showToast({
                      title: '图片上传失败，请稍后重试',
                      icon: 'none',
                    })
                  })
              })
              // await--上传图片之前先压缩，否则上传会比压缩先执行
              // console.log(image)

              // #endif
              // #ifndef APP-PLUS
              uni.showLoading({
                title: '图片上传中~',
              })
              _this.$api.files
                .uploadImg({
                  filePath: result.tempFilePaths[0],
                })
                .then(res => {
                  uni.hideLoading()
                  if (type === 0) {
                    // 营业执照

                    _this.imgurl = res.baseUrl + res.url
                    _this.readLicense(res.baseUrl + res.url)

                  } else if (type === 1) {
                    //法人身份证人像面
                    _this.faceimg = res.baseUrl + res.url

                  } else {
                    //法人身份证国徽面
                    _this.backimg = res.baseUrl + res.url

                  }

                })
                .catch(err => {
                  uni.hideLoading()
                  uni.showToast({
                    title: '图片上传失败，请稍后重试',
                    icon: 'none',
                  })
                })
              // #endif
              // console.log(f,result.tempFiles[0].size)

            },
          })
        },
      })
    },
    // 压缩
    compress(img) {
      console.log('开始压缩', img)
      let that = this
      return new Promise(res => {
        if (img.size > 504800) { //   如果大于500Kb进行压缩
          plus.zip.compressImage({
            src: img.path,
            dst: img.path,
            width: '60%',
            height: '60%',
            quality: 70,
            overwrite: true
          },
          event => {
            // console.log(event,'压缩后图片信息:' + JSON.stringify(event)) // 压缩后图片信息
            // this.imageInfo = event
            let newImg = event.target
            console.log(newImg)
            res(newImg) //返回新的图片地址，在uploadFile之前接收
          },
          )
        } else {
          res(img.path)
        }
      }, e => { // 返回错误信息
        console.log('Resolve file URL failed: ' + e.message)
      })
      // })
    },

    //提交
    async companyIdentity() {
      if (!this.typename) {
        uni.showToast({
          title: '请选择公司类型',
          icon: 'none',
        })
        return
      }
      if (!/^1[3456789]\d{9}$/.test(this.mobile)) {
        uni.showToast({
          title: '请填写法人手机号',
          icon: 'none',
        })
        return
      }
      if (!this.imgurl) {
        uni.showToast({
          title: '请上传营业执照照片',
          icon: 'none',
        })
        return
      }
      if (this.companyName !== this.imgCompanyName) {
        uni.showToast({
          title: '公司名与营业执照不匹配',
          icon: 'none',
        })
        // 公司营业执照不匹配
        this.notCompanyName = true
        return
      }
      // 当type(公司类型)为9/10洗车商时 不需要判断是否是法人和上传法人证件
      if (this.type !== 9 || this.type !== 10) {
        if (!this.isOwner && (!this.faceimg || !this.backimg)) {
          uni.showToast({
            title: this.faceimg
              ? '请上传法人身份证国徽面照片' : '请上传法人身份证人像面照片',
            icon: 'none',
          })
          this.notFace = this.faceimg ? true : false
          this.notBack = this.backimg ? true : false
          return
        }
      }
      if (this.isOwner && this.identityName !== this.legalname) {
        uni.showToast({
          title: '公司法人信息与身份信息不匹配，请仔细核对再次提交',
          icon: 'none',
        })
        this.notFace = true
        // this.$refs.uToast.show({
        //   title: '公司法人信息与身份信息不匹配，请仔细核对再次提交',
        // })
        return
      }

      uni.showLoading()
      try {
        let data = {
          name: this.companyName,
          address: this.address,
          type: this.type,
          legalname: this.legalname,
          mobile: this.mobile,
          licenseimg: this.imgurl,
          faceimg: this.isOwner ? this.identityFaceimg : this.faceimg,
          backimg: this.isOwner ? this.identityBackimg : this.backimg,
        }

        const res = await this.$api.user.companyIdentity(data)
        // if(res.cede==200){
        uni.hideLoading()
        if (this.addtype === 'add') {

          uni.showToast({
            title: '创建企业成功',
            duration: 2000,
          })
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages_login/enterCompany/enterCompany?phone='+this.registerPhone,
            })
          }, 2000)
        } else {
          this.quickLogin()
        }

        //   }else{

        //     uni.showToast({
        // title: res.msg,
        // duration: 2000,
        //       icon: 'none'
        //     })
        //   }
        // console.log(res,1111222222)
      } catch (e) {
        // console.log(e,222222)
        this.notFace = e.msg.indexOf('人像') == -1 ? false : true
        this.notBack = e.msg.indexOf('国徽') == -1 ? false : true
        if (e.msg.indexOf('身份信息') != -1) {
          this.notFace = true
          this.notBack = true
        }
        //TODO handle the exception
        uni.hideLoading()
      }
    },

    //图片读取
    async readLicense(imgurl) {
      try {
        const res = await this.$api.user.readLicense({
          imgurl,
        })
        this.imgCompanyName = res.data.name
        this.legalname = res.data.person
        this.address = res.data.address
        if (!this.checkImg) {
          this.$refs.popup.close()
        }
      } catch (e) {
        //TODO handle the exception
      }
    },

    //弹窗确认
    confirmImg() {
      this.$refs.popup.close()
    },

    //弹窗重新上传
    resetImg() {
      this.imgurl = ''
      this.imgCompanyName = ''
      this.legalname = ''
      this.address = ''
      this.$refs.popup.close()
    },

    async quickLogin() {
      try {
        const res = await this.$api.user.quickLogin({
          Mobile: this.$store.state.user.userInfo.mobile,
          IMEI: this.$store.state.user.imei,
        })
        this.loginSuccess(res.data)
      } catch (err) {
        // uni.hideLoading()
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages_login/login/login',
          })
        }, 2000)
      }
    },

    //保存登录信息
    loginSuccess(param) {
      this.$store.commit('user/setUserInfo', param)
      this.$store.commit('setUserInfo', param)
      //token存储
      // uni.setStorage({
      //   key: 'token',
      //   data: param.token,
      // })
      //用户信息存储
      // uni.setStorage({
      //   key: 'Ztc_B_USER_INFO',
      //   data: param,
      // })
      uni.setStorageSync('token', param.token)
      uni.setStorageSync('Ztc_B_USER_INFO', param)
      this.getUserInfo(() => {
        // uni.hideLoading()
        uni.showToast({
          title: '提交成功',
          duration: 2000,
        })
        uni.reLaunch({
          url: '/pages_login/enterCompany/enterCompany?phone='+this.registerPhone,
        })
      })
    },

    //获取用户信息
    async getUserInfo(cb) {
      try {
        const res = await this.$api.user.getUserInfo()
        uni.setStorageSync('userInfoDetail', res.data)
        this.$store.commit('setUserInfoDetail', res.data)
        cb()
      } catch (e) {
        //TODO handle the exception
        // uni.hideLoading()
        uni.reLaunch({
          url: '/pages_login/login/login',
        })
      }
    },
  },
}
